package pCloud;

import java.sql.*;

/**
 * Create connection to SQL database
 * @author anhdinh
 *
 */
public class SQLResourceConnection implements ResourceConnection{

	public static final String DEFAULT_DATABASE =  "jdbc:postgresql:postgres";
	static final String DEFAULT_USERNAME = "postgres";
	static final String DEFAULT_PW = "TuanAnh1984";
	String id, username, password;
	Connection conn;
	
	public SQLResourceConnection(String driver, String id, String username, String password){
		this.id = id;
		this.username = username;
		this.password = password;
		try {
			conn = createConnection(driver);
		} catch (Exception e) {
			System.err.println("Cannot establish connection to the database "+id);
			e.printStackTrace();
		}
	}
	
	private Connection createConnection(String driver) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{
		//String driver = "org.postgresql.Driver";	
		Class.forName(driver).newInstance();
		return DriverManager.getConnection(id,username,password);
	}
	
	@Override
	public String getResourceId() {
		// TODO Auto-generated method stub
		return this.id;
	}

	@Override
	public Object executeQuery(Object query) throws SQLException {
		String q = query.toString();
		Statement stmt = conn.createStatement();		
		ResultSet rs = stmt.executeQuery(q);		
		return rs;
	}

}

class SQLResourceFactory implements ResourceFactory{

	@Override
	public ResourceConnection createResourceConnection(String driver, String id, String username, String password) {
		// TODO Auto-generated method stub
		return new SQLResourceConnection(driver, id, username, password);
	}

}
